package com.example.teachingapi_6.utils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class ReservationTimeUpdater {

    // 数据库连接配置
    private static final String DB_URL = "jdbc:mysql://localhost:3306/hairdressing?serverTimezone=UTC";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "123456";

    public static void main(String[] args) {
        Connection conn = null;
        try {
            // 1. 注册JDBC驱动
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 2. 建立数据库连接
            conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);

            // 3. 获取需要更新的预约ID列表（状态不是"已取消"的）
            List<Integer> reservationIds = getReservationIds(conn);

            System.out.println("找到 " + reservationIds.size() + " 条需要更新的记录");

            // 4. 为每个预约生成时间序列并更新
            int processedCount = 0;
            for (int id : reservationIds) {
                boolean success = updateReservationTimes(conn, id);
                if (success) {
                    processedCount++;
                    if (processedCount % 10 == 0) {
                        System.out.println("已处理 " + processedCount + " 条记录");
                    }
                }
            }

            System.out.println("处理完成，共更新 " + processedCount + " 条记录");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 5. 关闭数据库连接
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 获取需要更新的预约ID列表
     */
    private static List<Integer> getReservationIds(Connection conn) throws SQLException {
        List<Integer> ids = new ArrayList<>();
        String sql = "SELECT id FROM m_reservation WHERE status != '已取消'";

        try (Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {

            while (rs.next()) {
                ids.add(rs.getInt("id"));
            }
        }

        return ids;
    }

    /**
     * 为单个预约生成时间序列并更新
     */
    private static boolean updateReservationTimes(Connection conn, int reservationId) {
        // 1. 获取预约的开始和结束时间
        String startTime = null;
        String endTime = null;

        String querySql = "SELECT sta_time, end_time FROM m_reservation WHERE id = ?";
        try (PreparedStatement pstmt = conn.prepareStatement(querySql)) {
            pstmt.setInt(1, reservationId);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    startTime = rs.getString("sta_time");
                    endTime = rs.getString("end_time");
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }

        if (startTime == null || endTime == null) {
            System.out.println("预约ID " + reservationId + " 缺少时间信息，跳过");
            return false;
        }

        // 2. 生成时间序列
        String timeSeries = generateTimeSeries(conn, startTime, endTime);

        // 3. 更新数据库
        String updateSql = "UPDATE m_reservation SET times = ? WHERE id = ?";
        try (PreparedStatement pstmt = conn.prepareStatement(updateSql)) {
            pstmt.setString(1, timeSeries);
            pstmt.setInt(2, reservationId);

            int affectedRows = pstmt.executeUpdate();
            return affectedRows > 0;
        } catch (SQLException e) {
            System.out.println("更新预约ID " + reservationId + " 时出错: " + e.getMessage());
            return false;
        }
    }

    /**
     * 生成时间序列字符串（每5分钟一个时间点）
     */
    private static String generateTimeSeries(Connection conn, String startTime, String endTime) {
        StringBuilder timeSeries = new StringBuilder();

        try {
            // 使用递归CTE生成时间序列
            String sql = "WITH RECURSIVE time_series AS (" +
                    "SELECT ? AS time_point " +
                    "UNION ALL " +
                    "SELECT DATE_ADD(time_point, INTERVAL 5 MINUTE) " +
                    "FROM time_series " +
                    "WHERE DATE_ADD(time_point, INTERVAL 5 MINUTE) < ?" +
                    ") " +
                    "SELECT GROUP_CONCAT(time_point ORDER BY time_point SEPARATOR ',') AS series " +
                    "FROM time_series";

            try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
                pstmt.setString(1, startTime);
                pstmt.setString(2, endTime);

                try (ResultSet rs = pstmt.executeQuery()) {
                    if (rs.next()) {
                        timeSeries.append(rs.getString("series"));
                    }
                }
            }
        } catch (SQLException e) {
            System.out.println("生成时间序列时出错: " + e.getMessage());
        }

        return timeSeries.toString();
    }
}